<template>
  <div class>
    <div ref="imageTest" style="width: 100%;position:relative;color:#333;display:flex;">
      <img
        v-if="certId == 1"
        src="http://img.visionbook.cn/iaoalevbig1.jpg"
        style="width:100%;"
        alt
      />
      <img
        v-if="certId == 2"
        src="http://img.visionbook.cn/iaoalevbig2.jpg"
        style="width:100%;"
        alt
      />
      <img
        v-if="certId == 3"
        src="http://img.visionbook.cn/iaoalevbig3.jpg"
        style="width:100%;"
        alt
      />
      <img
        v-if="certId == 4"
        src="http://img.visionbook.cn/iaoalevbig4.jpg"
        style="width:100%;"
        alt
      />
      <div
        style="position:absolute;top:52%;width:100%;text-align:center;font-size:50px;font-weight:bold;"
      >{{detailObj.userDetail.realName?detailObj.userDetail.realName:'暂未设置'}}</div>
      <div
        style="position:absolute;top:59%;width:100%;text-align:center;font-size:30px;font-weight:bold;"
      >{{detailObj.userDetail.pinyinName?detailObj.userDetail.pinyinName:'暂未设置'}}</div>
      <div
        style="position:absolute;left:14%;bottom:4%;padding-right:110px;font-size:18px;font-weight:bold;"
      >
        <div style="margin-bottom:20px;" id="qrcode" ref="qrcode"></div>
        <div style="width:100%;text-align:center;font-size:20px;">验证二维码</div>
      </div>
      <div
        style="position:absolute;bottom:5%;width:100%;text-align:right;padding-right:15%;font-size:18px;font-weight:bold;"
      >证书编号：{{detailObj.certificateNo}}</div>
      <!-- <div style="width: 1000px;margin:20px;" id="qrcode" ref="qrcode"></div>
      <div style="flex: 1;font-size:50px;margin-top:20px;">
        <div>证书名称：
          <span v-if="certId == 1">IAOA基础</span>
          <span v-else-if="certId == 2">IAOA提高</span>
          <span v-else-if="certId == 3">SIAOA</span>
          <span v-else-if="certId == 4">FIAOMC</span>
        </div>
        <div>真实姓名：{{detailObj.userDetail.realName?detailObj.userDetail.realName:'暂未设置'}}</div>
        <div>姓名拼音：{{detailObj.userDetail.pinyinName?detailObj.userDetail.pinyinName:'暂未设置'}}</div>
        <div>证书编号：{{detailObj.certificateNo}}</div>
      </div> -->
    </div>
    <div class="dialog-footer" style="text-align:center;padding: 30px 0">
      <el-button type="primary" @click="setCanvas">下载证书</el-button>
    </div>
  </div>
</template>

<script>
import { getUserCertificateIdDetail } from "@/api/user";

import QRCode from "qrcodejs2";
import html2canvas from "html2canvas";

export default {
  data() {
    return {
      certId: "",
      detailObj: {},
      certId: "",
      imgUrl: '',
      cvImg: '',
    };
  },
  created() {
    this.userId = this.$route.query.userId;
    this.certId = this.$route.query.certId;
    this.getDetail();
  },
  methods: {
    getDetail() {
      getUserCertificateIdDetail(this.userId, this.certId).then(res => {
        this.detailObj = res.data;
        setTimeout(() => {
          this.qrcode(this.userId, this.certId)
        }, 1000);
      });
    },
    qrcode (userId, certId) {
      let urlsss = `http://h5.visualbook.cn/search?userId=${userId}&certificateId=${certId}`
      let qrcode = new QRCode('qrcode', {
        width: 150,
        height: 150, // 高度
        text: urlsss, // 要生成二维码的链接（或当前页面地址）
      })
    },
    setCanvas() {
      let imgHeight = this.$refs.imageTest.offsetHeight
      console.log(imgHeight)
      const canvas = document.createElement("canvas");
      // 获取要生成图片的 DOM 元素
      let canvasDom = this.$refs.imageTest;
      // 获取指定的宽高
      const width = parseInt(window.getComputedStyle(canvasDom).width);
      const height = parseInt(window.getComputedStyle(canvasDom).height);
      console.log(width)
      console.log(height)
      // 宽高扩大 2 倍 处理图片模糊
      canvas.width = width * 2;
      canvas.height = height * 2;
      canvas.style.width = width / 2 + "px";
      canvas.style.height = height / 2 + "px";
      const context = canvas.getContext("2d");
      context.scale(1, 1);
      const options = {
        useCORS: true,
        width: document.documentElement.clientWidth,
        height: imgHeight,
        windowWidth: document.body.scrollWidth,
        windowHeight: document.body.scrollHeight,
        x:0,
        y:0
      };
      html2canvas(canvasDom, options).then(canvas => {
        // 生成图片地址
        this.imgUrl = canvas.toDataURL("image/jpeg", 1);
        this.cvImg = this.imgUrl;
        console.log(this.cvImg);
        this.downloadFile(`${this.detailObj.userDetail.realName?this.detailObj.userDetail.realName:'未命名'}`, this.cvImg);
      });
    },
    base64ToBlob(code) {
      let parts = code.split(";base64,");
      let contentType = parts[0].split(":")[1];
      let raw = window.atob(parts[1]);
      let rawLength = raw.length;

      let uInt8Array = new Uint8Array(rawLength);

      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
      }
      return new Blob([uInt8Array], { type: contentType });
    },
    downloadFile(fileName, content) {
      let aLink = document.createElement("a");
      let blob = this.base64ToBlob(content); //new Blob([content]);

      let evt = document.createEvent("HTMLEvents");
      console.log("点击下载", evt);
      evt.initEvent("click", true, true); //initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
      aLink.download = fileName;
      aLink.href = URL.createObjectURL(blob);

      // aLink.dispatchEvent(evt);
      aLink.click();
    },
  }
};
</script>